/**
 * @leaderStatus  这个是团长申请的状态字段 0 申请中 1 已通过 99 已拒绝
 * @memberLeaderType 这个是团长类型字段  1 团长 2 副团长
 * @leaderId 这个是团长id
 */

var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../services/user.js');
var app = getApp();

Page({
    data: {
        goodsList:[],
        userInfo: {},
        couponNum:0,
        addressInfo:null,
        latitude: "",
        scale:17,
        longitude: "",
        markers: [],
        circles: [],
        showCodeImg:false,
        codeImg:'',
        leaderId:'',
        activityId:''
    },
    onPullDownRefresh: function () {
        let _this = this;
        _this.onShow();
        wx.stopPullDownRefresh();
    },
    onLoad: function(options) {
        // 页面初始化 options为页面跳转所带来的参数
        console.log(app.globalData)
        this.getDeliveryCode();
        this.getRecommendGoodList();
        // if(options.from){
        //     // 是否接受副团长邀请页面跳转过来的
        //     this.getMemberInfo();
        // }
        let that = this
        const userInfo = wx.getStorageSync('userInfo');
        console.log(userInfo)
        if(options.leaderId != undefined){
            wx.setStorageSync('leaderId', options.leaderId);
            wx.setStorageSync('activityId', options.activityId);
            this.setData({
                leaderId:options.leaderId,
                activityId:options.activityId
            })
            console.log(that.data.leaderId,that.data.activityId)
            let url='';
            if(userInfo.memberLeaderType.value == 1){
                url = "/Leader/ucenter/ucenter?rs=1";
            }else if(userInfo.memberLeaderType.value == 2){
                url = "/Leader/ucenter/ucenter?rs=2";
            }else{
                url = "/Leader/application/head-application/head-application?leaderId="+that.data.leaderId+'&activityId='+that.data.activityId
            }
            return wx.navigateTo({
                url
            })
        }
    },
    onReady: function() {

    },
    onShow: async function() {
        await this.getMemberInfo();
        //setTimeout(()=>{
            let userInfo = wx.getStorageSync('userInfo');
            let token = wx.getStorageSync('token');
            // 页面显示
            if (userInfo && token) {
                app.globalData.userInfo = userInfo;
                app.globalData.token = token;
            }
            this.setData({
                userInfo: app.globalData.userInfo,
            });
            this.getAddressInfoList()
            // this.getCouponList();
        //},1500);
        if(app.globalData.cartNum > 0){
            wx.setTabBarBadge({
                index: 3,
                text: app.globalData.cartNum.toString()
            })
        }else{
            wx.removeTabBarBadge({index:3})
        }
    },
    onHide: function() {
        // 页面隐藏

    },
    onUnload: function() {
        // 页面关闭
    },
    getRecommendGoodList(){
        this.findGoodsRequest({
          isRecommend: true
        }).then(res=>{
          console.log(1223,res.result)
          if(res.result.length > 0){
            this.setData({
              goodsList:res.result,
            })
            console.log(222,this.data.goodsList)
          }
        }).catch(err=>{
          console.log(err.message)
        })
      },
    findGoodsRequest(data = {}){
        wx.showLoading({
          title: "正在加载"
        })

        let url = api.indexUrl.getGoodList+'?current=1&size=21';

        return new Promise((resolve, rejected)=>{
          util.request(url, data, "POST").then((res)=>{
            resolve(res);
            wx.hideLoading();
          }).catch(err=>{
            rejected(err);
            wx.hideLoading();
          })
        })
    },
    getAddressInfoList:function() {
        let _this = this;
        // let location = wx.getStorageSync('memberLeaderObj');
        // console.log(location)
        // if(location){
        //     _this.setData({
        //         addressInfo:location
        //     })
        //     return
        // }
         wx.getLocation({
            type:'wgs84',
            success:function(res){

                util.request(api.findAddressInfoList+'?lat='+res.latitude+'&lon='+res.longitude).then(result=>{
                    const chooseItem = result.result.find(item => item.isChoose) || result.result[0];
                    _this.setData({
                        addressInfo: chooseItem,

                    markers: [{
                      id: "1",
                      latitude: chooseItem.lat,
                      longitude: chooseItem.lon,
                      width: 30,
                      height: 30,
                      iconPath: "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/icon_position.png",
                      title: chooseItem.storeName + '|' + chooseItem.storeAddress

                    }],
                    circles: [{
                      latitude: chooseItem.lat,
                      longitude: chooseItem.lon,
                      color: '#FF0000DD',
                      fillColor: '#7cb5ec88',
                      radius: 100,
                      strokeWidth: 1
                    }]
                    })
                }).catch(err=>{
                    console.log(err)
                })

            },
            fail:function(err){
                console.log(err)
            }
        });

    },
    getCouponList:function(){
        let _this = this;
        util.request(api.couponList,{status:1}).then(res=>{
            _this.setData({
                couponNum:res.result.length
            })
            app.globalData.couponList = res.result;
        }).catch(err=>{
            console.log(err)
        })

    },
    goLogin() {
        if(app.globalData.userInfo && app.globalData.userInfo.phone){
            return false
        }
        wx.navigateTo({
            url: '/pages/authorized/index'
        })
    },
    goMember() {
        if(app.globalData.userInfo && app.globalData.userInfo.phone){
            wx.navigateTo({
                url: '/pages/member/member'
            })
            return ;
        }
        this.goLogin();
    },
    goOrder(e){
        if(app.globalData.userInfo && app.globalData.userInfo.phone){
            const status = e.currentTarget.dataset.status;
            let url = '/pages/order/order'
            if(status){
                url += "?status=" + status
            }
            wx.navigateTo({
                url
            })
            return ;
        }
        this.goLogin();
    },
    showCodeImg() {
        this.setData({
            showCodeImg:true
        })
    },

    hideCodeImg() {
        this.setData({
            showCodeImg:false
        })
    },
    getDeliveryCode() {
        let _this = this;
        util.request(api.getDeliveryCode).then(res=>{
            _this.setData({
                codeImg:res.message
            })
            console.log(1,res)
        }).catch(err=>{
            console.log(err)
        })
    },
    goAddress(){
        if(app.globalData.userInfo && app.globalData.userInfo.phone){
            wx.navigateTo({
                url: '/pages/addressList/addressList'
            })
            return ;
        }
        this.goLogin();
    },
    exitLogin: function() {
        wx.showModal({
            title: '',
            confirmColor: '#b4282d',
            content: '退出登录？',
            success: function(res) {
                if (res.confirm) {
                    wx.removeStorageSync('token');
                    wx.removeStorageSync('userInfo');
                    wx.switchTab({
                        url: '/pages/index/index'
                    });
                }
            }
        })

    },
    goToLeader(){
        let that = this
        if(app.globalData.userInfo && app.globalData.userInfo.phone){
            const userInfo = app.globalData.userInfo;
            let url = "";
            // 1 申请中 2 已通过 99 已拒绝
            switch(userInfo.leaderStatus.value){
                case 1:
                    url = "/Leader/application/application-result/application-result?rs=0";
                    break;
                case 99:
                    url = "/Leader/application/application-result/application-result?rs=1";
                    break;
                default:
                    if(userInfo.memberLeaderType.value == 1){
                        url = "/Leader/ucenter/ucenter?rs=1";
                    }else if(userInfo.memberLeaderType.value == 2){
                        url = "/Leader/ucenter/ucenter?rs=2";
                    }else {
                        if(that.data.leaderId){
                            url = "/Leader/application/head-application/head-application?leaderId="+that.data.leaderId+'&activityId='+that.data.activityId
                        } else {
                            url = "/Leader/application/head-application/head-application"
                        }
                        
                    }
            }
            return wx.navigateTo({
                url
            })
        }
        this.goLogin();

    },
    goToMerchant(){
        if(app.globalData.userInfo && app.globalData.userInfo.phone){
            const userInfo = app.globalData.userInfo;
            let url = "";
            // merchantStatusApply 0:未申请，1：申请中，2.申请成功，99，拒绝申请
            console.log("12312");
            switch(userInfo.merchantStatusApply.value){
                case 1:
                    url = "/Leader/application/application-result/application-result?rs=0";
                    break;
                case 99:
                    url = "/Leader/application/application-result/application-result?rs=1";
                    break;
                case 2:
                    if(userInfo.merchantType.value == 1){
                        url = "/Surroundings/ucenter/ucenter?rs=1";
                    }else{
                        url = "/Surroundings/ucenter/ucenter?rs=2";
                    }
                    break;
                default:
                    url = "/Surroundings/application/application"
            }
            return wx.navigateTo({
                url
            })
        }
        this.goLogin();
    },
    goToSupplier(){
        if(app.globalData.userInfo && app.globalData.userInfo.phone){
            const userInfo = app.globalData.userInfo;
            let url = "";
            // supplierStatus 0:未申请，1：申请中，2.申请成功，99，拒绝申请

            switch(userInfo.supplierStatus.value){
                case 1:
                    url = "/pages/supplier/application/application-result/application-result?status=1";
                    break;
                case 99:
                    url = "/pages/supplier/application/application-result/application-result?status=99";
                    break;
                case 2:
                    url = "/pages/supplier/index/index";
                    break;
                case 3:
                    url = "/pages/supplier/index/index";
                    break;
                default:
                    url = "/pages/supplier/application/supplier-application/supplier-application"
            }
            return wx.navigateTo({
                url
            })
        }
        this.goLogin();
    },
    goToWholesalers(){
        if(app.globalData.userInfo && app.globalData.userInfo.phone){
            const userInfo = app.globalData.userInfo;
            let url = "";
            // supplierStatus 0:未申请，1：申请中，2.申请成功，99，拒绝申请

            switch(userInfo.wholesalerStatus.value){
                case 1:
                    url = "/pages/wholesalers/application/application-result/application-result?status=1";
                    break;
                case 99:
                    url = "/pages/wholesalers/application/application-result/application-result?status=99";
                    break;
                case 2:
                    url = "/pages/wholesalers/hot/hot";
                    break;
                default:
                    url = "/pages/wholesalers/application/saler-application/saler-application"
            }
            return wx.navigateTo({
                url
            })
        }
        this.goLogin();
    },
    getMemberInfo() {
        let _this = this;
        return new Promise((resolve,rejected)=>{
            wx.showLoading();
            util.request(api.MemberInfo).then(res=>{
                _this.setData({
                    userInfo:res.result
                })
                app.globalData.userInfo = res.result;
                app.globalData.cartNum = res.result.shoppingCartCount
                wx.setStorageSync("userInfo",res.result);
                wx.hideLoading();
                resolve();
            }).catch(err=>{
                console.log(err)
                rejected();
            })
        })
    },
})
